package android.tusnotas.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ExpandableListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.tusnotas.activities.extras.ShowCourseActivityExtras;
import android.tusnotas.activities.extras.ShowInstancesActivityExtras;
import android.tusnotas.beans.Course;
import android.tusnotas.beans.Instance;
import android.tusnotas.model.TusNotasModel;
import android.tusnotas.receivers.VersionReceiver;
import android.tusnotas.services.WebCheckerManager;
import android.tusnotas.util.AlertBuilder;
import android.tusnotas.util.Devel;
import android.tusnotas.util.Properties;
import android.tusnotas.util.PropertyLoader;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ShowInstancesActivity extends ExpandableListActivity{
	
	private List<Instance> instances;
	private Map<Integer, Integer> instancesMap;
	private WebCheckerManager webCheckerManager = null;
	private Menu menu = null;
	private KillReceiver mKillReceiver;
	private VersionReceiver versionReceiver;
	
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	mKillReceiver = new KillReceiver();
		IntentFilter intentFilter = new IntentFilter("kill");
		registerReceiver(mKillReceiver,	intentFilter);
	
		versionReceiver = new VersionReceiver("ShowInstancesActivity",this);
		IntentFilter intentVersionFilter = new IntentFilter("version");
		registerReceiver(versionReceiver, intentVersionFilter);
		
		setContentView(R.layout.show_instances);
		setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    	long begin = System.currentTimeMillis();
    	
    	webCheckerManager = new WebCheckerManager(this);
    	TusNotasModel tnm = TusNotasModel.getTusNotasModel(getApplicationContext());
    	
		Boolean fromConfiguration = getIntent().getBooleanExtra(ShowInstancesActivityExtras.FROM_LOGIN,Boolean.FALSE);
		if (fromConfiguration){
			getIntent().removeExtra(ShowInstancesActivityExtras.FROM_LOGIN);
			webCheckerManager.startWebChecker();
		}
		
	    if (PropertyLoader.USERNAME == null || PropertyLoader.USERNAME.trim().equals("") || PropertyLoader.NUM_WRONG_PASS == -1){
	    	Intent welcomeIntent = new Intent(this, Login.class);
	    	startActivity(welcomeIntent);
	    	finish();
	    	return;
	    }
    	
	    this.instances = tnm.selectAllInstances();
        drawList();
        if (Devel.fullDevel || Devel.showInstancesDevel){
        	Log.w(this.getClass().getName(), "Show Instances displayed OK in: " + (System.currentTimeMillis() - begin));
        }
    }
    
    public void gotoCourse(View view){
    	TextView tv = (TextView) ((View) view.getParent()).findViewById(R.id.course_id);
    	Intent showCourseIntent =  new Intent(getApplicationContext(), ShowCourse.class);
    	showCourseIntent.putExtra(ShowCourseActivityExtras.COURSE_ID, Integer.parseInt(tv.getText().toString()));
		startActivity(showCourseIntent);
    }
	
    @Override
    public boolean onPrepareOptionsMenu(Menu myMenu) {
	    menu = myMenu;
	    menu.clear();
	    MenuInflater inflater = getMenuInflater();
	    if (webCheckerManager.isWebCheckerStarted()){
	    	inflater.inflate(R.menu.menu_instances_started, menu);
	    }
	    else{
	    	inflater.inflate(R.menu.menu_instances_stopped, menu);
	    }
	    return Boolean.TRUE;
    }
    
    
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case R.id.configuration:
		    	Intent welcomeIntent = new Intent(this, Login.class);
		    	startActivity(welcomeIntent);
	            return Boolean.TRUE;
	            
	        case R.id.stop:
	        	Toast t = Toast.makeText(getApplicationContext(), R.string.toast_service_stop, Toast.LENGTH_SHORT);
	        	t.setGravity(Gravity.CENTER, 0, 0);
	        	t.show();
	        	webCheckerManager.stopWebChecker();
	        	onPrepareOptionsMenu(menu);
	        	return Boolean.TRUE;
	        	
	        case R.id.start:
	        	Toast t1 = Toast.makeText(getApplicationContext(), R.string.toast_service_start, Toast.LENGTH_SHORT);
	        	t1.setGravity(Gravity.CENTER, 0, 0);
	        	t1.show();
	        	webCheckerManager.startWebChecker();
	        	onPrepareOptionsMenu(menu);
	            return Boolean.TRUE;
	            
	        case R.id.refresh:
	        	refresh(Boolean.TRUE);
	    		Toast t2 = Toast.makeText(getApplicationContext(), R.string.toast_refresh, Toast.LENGTH_SHORT);
	    		t2.setGravity(Gravity.CENTER, 0, 0);
	    		t2.show();
	        	return Boolean.TRUE;
	        	
	        case R.id.about:
	        	AlertBuilder.showAboutInfo(this);
	        	return Boolean.TRUE;
	        	
			case R.id.logout:
				// delete old hash
				TusNotasModel.getTusNotasModel(getApplicationContext()).updateProperty(Properties.HASH, "");
				Log.e(getClass().getName(),"Deleted saved hash");
				
				webCheckerManager.stopWebChecker();
				AlertBuilder.logout(this);
				return Boolean.TRUE;

	        default:
	            return super.onOptionsItemSelected(item);
        }
	}
	
	private List<Map<String,String>> createGroupList() {
		this.instancesMap = new HashMap<Integer, Integer>();
		List<Map<String,String>> result = new ArrayList<Map<String,String>>();
		Integer i=0;
		for(Instance ins : this.instances){
			this.instancesMap.put(ins.getId(), i++);
			Map<String,String> m = new HashMap<String,String>();
			m.put("instanceName", ins.getDescription());
			result.add(m);
		}
		
		return result;
	}

	private List<List<Map<String,String>>> createChildList() {
		
    	TusNotasModel tnm = TusNotasModel.getTusNotasModel(getApplicationContext());

		List<List<Map<String,String>>> result = new ArrayList<List<Map<String,String>>>();
		for(Instance instance : this.instances){
			List<Map<String,String>> secList = new ArrayList<Map<String,String>>();
			for(Course course : tnm.selectCoursesByInstance(instance.getId())){
				Map<String,String> child = new HashMap<String,String>();
				child.put("courseId", course.getId().toString());
				child.put("courseName", course.getName());
				secList.add(child);
			}
			result.add(secList);
		}
		return result;
	}
	
	private void drawList() {
		
		SimpleExpandableListAdapter expListAdapter =
			new SimpleExpandableListAdapter(
				this,
				createGroupList(),
				R.layout.instance_item,
				new String[] { "instanceName"},
				new int[] { R.id.instance_desc},
				createChildList(),
				R.layout.course_item,
				new String[] { "courseId", "courseName"},
				new int[] { R.id.course_id, R.id.course_desc}
			);
		
		setListAdapter(expListAdapter);
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
		return Boolean.FALSE;
	}
	
	public void expandInstance(Integer instanceId){
		if (this.instancesMap.get(instanceId) != null){
			getExpandableListView().expandGroup(this.instancesMap.get(instanceId));
		}
	}
	
	public void refresh(Boolean keepStatus){

		List<Integer> expandedPositions = null;
		ExpandableListView expandableListView = null;
		
		Integer top = 0;
		Integer index = 0;
		
		if (keepStatus){
			expandableListView = getExpandableListView();
			index = expandableListView.getFirstVisiblePosition();
			View v = expandableListView.getChildAt(0);
			top = (v == null) ? 0 : v.getTop();
			expandedPositions = new ArrayList<Integer>();
			for (int i=0; i<expandableListView.getChildCount(); i++){
				if (expandableListView.isGroupExpanded(i)){
					expandedPositions.add(i);
				}
			}
		}
		
		this.instances = TusNotasModel.getTusNotasModel(getApplicationContext()).selectAllInstances();
        
		drawList();
		if (keepStatus){
			for (Integer expandedPosition : expandedPositions) {
				expandableListView.expandGroup(expandedPosition);
			}
			expandableListView.setSelectionFromTop(index, top);

		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mKillReceiver);
		unregisterReceiver(versionReceiver);
	}
	
	private final class KillReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }
	
	public void askUserForNewAppVersion(){
		_askUserForNewAppVersion();
	}

	private void _askUserForNewAppVersion(){
		Log.i(getClass().getSimpleName(), "Download version");
	}
}